package com.leezk.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leezk.order.entity.Student;
import com.leezk.order.exception.NoDataException;
import com.leezk.order.mapper.StudentMapper;
import com.leezk.order.service.IStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leezk.order.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author leotong
 * @since 2022-03-16
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {

    private final StudentMapper studentMapper;

    @Autowired
    public StudentServiceImpl(StudentMapper studentMapper) {
        this.studentMapper = studentMapper;
    }

    @Override
    public Map<String,String> login(String username, String password) {
        QueryWrapper<Student> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("account",username);
        Student student = this.getOne(queryWrapper);
        if (student==null){
            throw new NoDataException("当前用户不存在");
        }
        if (!student.getPassword().equals(password)){
            throw new NoDataException("密码输入错误，请重新输入");
        }
        Map<String,String> result=new HashMap<>();
        result.put("studentId",student.getId().toString());
        result.put("token",StringUtil.createToken());
        //生成登陆token
        return result;
    }

    @Override
    public Page<Student> getStudent(Page<Student> page) {
        return studentMapper.selectPage(page, null);
    }

    @Override
    public boolean registerStudent(Student student) {
        QueryWrapper<Student> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("account", student.getAccount());
        Student result = studentMapper.selectOne(queryWrapper);
        if (result!=null){
            throw new NoDataException("当前账号已经被使用，请重新输入");
        }
        return save(student);
    }
}
